import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUsers, getUserDetail, createUser, updateUser, deleteUser } from '@/request/user-role-api'
import type { User, PageQueryParams, UserCreateRequest, UserUpdateRequest } from '@/model/user-role-model'

/**
 * 用户管理模块的Store
 */
export const useUserStore = defineStore('user', () => {
  // 用户列表
  const userList = ref<User[]>([])
  // 用户总数
  const userTotal = ref(0)
  // 当前用户
  const currentUser = ref<User | null>(null)
  // 加载状态
  const loading = ref(false)

  /**
   * 获取用户列表
   * @param params 查询参数
   */
  async function fetchUserList(params?: PageQueryParams) {
    loading.value = true
    try {
      const res = await getUsers(params)
      if (res.code === 0) {
        // 判断返回的data是数组还是包含users和total的对象
        if (Array.isArray(res.data)) {
          userList.value = res.data
          userTotal.value = res.total || 0
        } else if (res.data && 'users' in res.data) {
          userList.value = res.data.users
          userTotal.value = res.data.total || 0
        }
      } else {
        console.error('获取用户列表失败:', res.errorMsg)
      }
    } catch (error) {
      console.error('获取用户列表出错:', error)
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取用户详情
   * @param userId 用户ID
   */
  async function fetchUserDetail(userId: number) {
    loading.value = true
    try {
      const res = await getUserDetail(userId)
      if (res.code === 0 && res.data) {
        currentUser.value = res.data
      } else {
        console.error('获取用户详情失败:', res.errorMsg)
      }
    } catch (error) {
      console.error('获取用户详情出错:', error)
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建用户
   * @param userData 用户数据
   */
  async function addUser(userData: UserCreateRequest) {
    loading.value = true
    try {
      const res = await createUser(userData)
      loading.value = false
      return res
    } catch (error) {
      console.error('创建用户出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 更新用户
   * @param userId 用户ID
   * @param userData 用户数据
   */
  async function updateUserInfo(userId: number, userData: UserUpdateRequest) {
    loading.value = true
    try {
      const res = await updateUser(userId, userData)
      loading.value = false
      return res
    } catch (error) {
      console.error('更新用户出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 删除用户
   * @param userId 用户ID
   */
  async function removeUser(userId: number) {
    loading.value = true
    try {
      const res = await deleteUser(userId)
      loading.value = false
      return res
    } catch (error) {
      console.error('删除用户出错:', error)
      loading.value = false
      throw error
    }
  }

  /**
   * 清空当前用户
   */
  function clearCurrentUser() {
    currentUser.value = null
  }

  return {
    userList,
    userTotal,
    currentUser,
    loading,
    fetchUserList,
    fetchUserDetail,
    addUser,
    updateUserInfo,
    removeUser,
    clearCurrentUser
  }
})
